<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
 
/**
 * order aggregator(商品促销规则 组合条件)
 * $ 2010-05-16 18:32 $
 */
class b2c_sales_order_aggregator_subselect extends b2c_sales_order_aggregator
{
    public function getItem() {
        // 其实一个aggregator 只有一条记录的哈
        return array(
                   'b2c_sales_order_aggregator_subselect' => array(
                                       'name'=>app::get('b2c')->_('商品子查询'),
                                       'object'=>'b2c_sales_order_aggregator_subselect',
                                       'support'=>array(
                                                     'item'=>array(
                                                                'goods'=>app::get('b2c')->_('-----商品属性-----'),
                                                                'subgoods'=>app::get('b2c')->_('-----商品扩展属性-----'),
                                                             )
                                                  ),
                                      )
               );
    }

    // 标准数据格式
    public function getDefaultStandardData() {
        $aTemp  = $this->getItem();
        $aStandard['attribute']['options'] = $this->getAttributes(array('subgoods'));
        $aStandard['operator']['options'] = $this->getOperators(array('equal','equal1'));
        return array(
                    'type'=> array(
                                'input'=> 'hidden',
                                'desc'=> null,
                                'default'=> $this->default,    // 默认值 如果有模板设置 按模板设定 如果有值 则按值的
                                'support'=>$aTemp[get_class($this)]['support'],
                    ),
                    'attribute'=> array(
                                        'input'=> 'select', // select | hidden
                                        'vtype'=> null,     // 验证类型(保留)
                                        'desc'=> null,      // 描述 标准为空 如果为空的话 使用default的名称 只在input='hidden'时有效
                                        'options'=> $aStandard['attribute']['options'],
                                        'default'=> null    // 默认值 如果有模板设置 按模板设定 如果有值 则按值的
                                ),
                    'operator'=> array(
                                        'input'=> 'select', // select | hidden
                                        'vtype'=> null,     // 验证类型(保留)
                                        'desc'=> null,      // 描述 标准为空 如果为空的话 使用default的名称 只在input='hidden'时有效
                                        'options'=> $aStandard['operator']['options'],
                                        'default'=> null    // 默认值 如果有模板设置 按模板设定 如果有值 则按值的
                                ),
                    'value'=> array(
                                    'input'=> 'text', // select | hidden
                                    'vtype'=> 'number',     // 验证类型(保留)
                                    'desc'=> null,    // 描述 标准为空 如果为空的话 使用default的名称 只在input='hidden'时有效
                                    'default'=> null  //
                             ),
                    'conditions'=> array()
              );
    }

    /**
     * 标准数据格式(结合模板和数据)
     *
     * @param array $aTamplate
     * @param array $aData
     */
    public function getStandardData($aTamplate = array(),$aData = array()) {
        $aStandard = $this->getDefaultStandardData();
        // 为空返回标准格式
        if(empty($aTamplate) && empty($aData)) return $aStandard;

        return $this->_getStandardData($aStandard,$aTamplate,$aData);
    }

    /**
     * 标准数据格式(结合模板和数据)(实际处理 重载此方法就行了)
     *
     * @param array $aStandata
     * @param array $aTamplate
     * @param array $aData
     */
    protected function _getStandardData($aStandard,$aTamplate,$aData) {
        /////////////////////////// type //////////////////////////
        $aStandard['type'] = $this->_makeStandardData($aStandard['type'],$aTamplate['type'],$aData['type']);

        /////////////////////////// attribute //////////////////////////
        $aStandard['attribute'] = $this->_makeStandardData($aStandard['attribute'],$aTamplate['attribute'],$aData['attribute']);
        $aStandard['attribute']['options'] = $this->getAttributes(array('subgoods'));
        /////////////////////////// operator //////////////////////////
        $aStandard['operator'] = $this->_makeStandardData($aStandard['operator'],$aTamplate['operator'],$aData['operator']);
        $aStandard['operator']['options'] = $this->getOperators(array('equal','equal1'));

        ////////////////////// aggregator value ///////////////////////
        $aStandard['value'] = $this->_makeStandardData($aStandard['value'],$aTamplate['value'],$aData['value']);

        return $aStandard;
    }

        /**
     * 生成后台模板(真正集合器的处理)
     *
     * @param array $aStandard
     * @param string $html
     * @param string $vpath
     * @param int $level
     * @param int $position
     * @param boolean $is_auto
     */
    protected function _view($aStandard,$html,$vpath,$level,$position,$is_auto) {
        $sAggregator = '';
        $sAuto = '';
        $sAuto1 = '';

        // type
        $sAggregator .= $this->_standard_view($aStandard['type'],($vpath."[type]"),$level,$position,$is_auto);
        if(empty($sAggregator)) return false; // 没有type怎么能活呢

        // attribute
        $sAggregator .= $this->_standard_view($aStandard['attribute'],($vpath."[attribute]"),$level,$position,$is_auto);
        if(empty($sAggregator)) return false; // 没有attribute怎么能活呢

        // operator
        $sAggregator .= $this->_standard_view($aStandard['operator'],($vpath."[operator]"),$level,$position,$is_auto);
        if(empty($sAggregator)) return false; // 没有attribute怎么能活呢

        // value
        $sAggregator .= $this->_standard_view($aStandard['value'],($vpath."[value]"),$level,$position,$is_auto);
        if(empty($sAggregator)) return false; // 没有value怎么能活呢
        
        $sAggregator .= '<span class="lnk" onclick="showConditions(this)">'.app::get('b2c')->_('[添加一个条件]').'</span>';

        if($is_auto) {
            $sAuto = $this->wrap_li($this->makeConditionOptions($aStandard['type'],$vpath,$level));// 如果自动配置的话 这个得有条件的处理
            $sAuto1 = $this->create_auto();
        }

        $html = $this->wrap_div($sAggregator).$this->wrap_ul($html.$sAuto);
        $html = (is_null($position))? $this->wrap_div($html).$sAuto1 : $html;
        return $html;
    }
    

    //  public function validate($cart_objects,$aCondition) {
    
    // 集合器的处理(subselect) 只处理goods的
     public function validate($cart_objects,$aCondition) {

        if (empty($aCondition['conditions']) || empty($aCondition['attribute']) || empty($aCondition['operator']) ) return false;
        // subselect attribute
        $aAttr = $this->getAttribute($aCondition['attribute']);//subgoods_quantity



        $total = 0;

        // todo subselect下的condtions 都是必须满足的 以all的形式出现
        // value 设计相冲突了 不过value不般不可能为0
        $aCondition['aggregator'] = 'all';

        $oCond = kernel::single($this->default);  //b2c_sales_order_aggregator_combine

          //首批打折促发 @mo
       $pre_type1 = app::get('b2c')->_('FirstDiscount');
       $pre_type2 = app::get('b2c')->_('Fullofgifts');

        if(isset($aCondition['type2']) &&  $aCondition['type2'] ==$pre_type1)
        {
    //uset会释放元数组元素@mo

           //根据促销条件获取相应促销条件开始的时间
            $pre_rule = app::get('b2c')->model('sales_rule_order');
            $is_statue = "true";
            $filter_c = array('status|nequal'=>$is_statue);
            $all_promotion_rules = $pre_rule->getList('rule_id,conditions,from_time,to_time', $filter_c, 0, -1, 'rule_id ASC');

    
           
          foreach ($all_promotion_rules as $key => $value) {
              if(isset($value['conditions']['conditions'][0]['type2']) && $value['conditions']['conditions'][0]['type2'] == $aCondition['type2'])
              {
                    $index = $key;


              }
         
          }
           $member_id = kernel::single('b2c_user_object')->get_member_id();

            $db_order = app::get('b2c')->model('orders');
          if($index !=null)
          {
             $fromtime = $all_promotion_rules[$index]['from_time'];
             $totime = $all_promotion_rules[$index]['to_time'];
               
             $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime,'status|noequal'=>'dead');//modify by hzk 05-26 排除废单 status = dead

          }
          else
          {
             $filter = array('member_id'=>$member_id);//time: ,'createtime|bthan'=>$this_time
          }
       
           //根据当前的促销条件到订单中心去获取当前这个人已经购买的数量
            //$this_time = 1490839659;// $aCondition['time'];
           
            //$filter = array('member_id'=>$member_id);//time: ,
            $this_member_all_orders = $db_order->getList('order_id,member_id', $filter, 0, -1, 'order_id ASC');

  
            $db_order_goods = app::get('b2c')->model('order_items');
            $gift_type = app::get('b2c')->_('product');

            $order_goods_nums = 0;//当前用户之前购买的数量
            foreach ($this_member_all_orders as $one_order) {
                $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$aCondition['conditions']['0']['value']);
                $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                if(!empty($temp_goods))
                {
                    $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                    
                }

                //能否促发首批打折的条件就是，当前用户以前购买该商品的数量是否小于限制
               //$order_goods_nums  与$aCondition['firstvalue']大小比较
            }
           
            $aOperator = $this->getOperator($aCondition['operator']);
         return kernel::single($aOperator['object'])->validate($aCondition['operator'], $aCondition['firstvalue'], $order_goods_nums);
          
        }
         else
        {
            foreach ($cart_objects['object']['goods'] as $object) {
                if ($oCond->validate($object, $aCondition)) { 
            
                    $total += (float) $this->getData($object, $aAttr['path']);

                }   
            }
        $aOperator = $this->getOperator($aCondition['operator']);
         return kernel::single($aOperator['object'])->validate($aCondition['operator'], $aCondition['value'], $total);
        }
        /*
        
          //@mo 2017年4月14日 14:14:45 //判断满赠促销
            else if (isset($aCondition['type2']) &&  $aCondition['type2'] ==$pre_type2) {
           //这里是满赠促销限制购买数量
           //根据促销条件获取相应促销条件开始的时间
            $pre_rule = app::get('b2c')->model('sales_rule_order');
            $is_statue = "true";
            $filter_c = array('status|nequal'=>$is_statue);
            $all_promotion_rules = $pre_rule->getList('rule_id,conditions,from_time,to_time', $filter_c, 0, -1, 'rule_id ASC');
          
          $index = null;
  
           
          foreach ($all_promotion_rules as $key => $value) {
              if(isset($value['conditions']['conditions'][0]['type2']) && $value['conditions']['conditions'][0]['type2'] == $aCondition['type2'])
              {
                    $index = $key;


              }
         
          }
           $member_id = kernel::single('b2c_user_object')->get_member_id();

            $db_order = app::get('b2c')->model('orders');
          if($index !=null)
          {
             $fromtime = $all_promotion_rules[$index]['from_time'];
             $totime = $all_promotion_rules[$index]['to_time'];
               
             $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime);

          }
          else
          {
             $filter = array('member_id'=>$member_id);//time: ,'createtime|bthan'=>$this_time
          }
       
           //在该促销时间之内用户所下的订单
            $this_member_all_orders = $db_order->getList('order_id,member_id', $filter, 0, -1, 'order_id ASC');

  
            $db_order_goods = app::get('b2c')->model('order_items');
            $gift_type = app::get('b2c')->_('product');

            $order_goods_nums = 0;//当前用户之前购买的数量
            foreach ($this_member_all_orders as $one_order) {
                $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$aCondition['conditions']['0']['value']);
                //根据订单，获取购买了当前条件的商品
                $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                if(!empty($temp_goods))
                {
                    $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                    
                }
                
            }
            $less_than_max_number = false;
            //判断当前最大的购买数量
             if($order_goods_nums < $aCondition['maxquantity'])
                $less_than_max_number = true;

            //下面是判断当前购物车该商品的数量是否大于条件中的数量
            foreach ($cart_objects['object']['goods'] as $object) {
                if ($oCond->validate($object, $aCondition)) { 
            
                    $total += (float) $this->getData($object, $aAttr['path']);

                }   
            }
            $aOperator = $this->getOperator($aCondition['operator']);
            $more_than_condition_number =  kernel::single($aOperator['object'])->validate($aCondition['operator'], $aCondition['value'], $total);
            if($less_than_max_number && $more_than_condition_number)
                return true;
            else
                return false;
        }*/
       
      
    }

    /*
    重新写控制判断当前条件是否符合
     */
     // 集合器的处理(subselect) 只处理goods的
    public function validate_new($cart_objects,$aCondition,$rule) {
// echo 'xxx001';
// var_dump($rule);
        //$aCondition =   $rule['conditions']['conditions'][0];
        if (empty($aCondition['conditions']) || empty($aCondition['attribute']) || empty($aCondition['operator']) ) return false;
        // subselect attribute
        $aAttr = $this->getAttribute($aCondition['attribute']);//subgoods_quantity

        
       
        //exit;

        $total = 0;

        // todo subselect下的condtions 都是必须满足的 以all的形式出现
        // value 设计相冲突了 不过value不般不可能为0
        $aCondition['aggregator'] = 'all';

        $oCond = kernel::single($this->default);  //b2c_sales_order_aggregator_combine

       
          //首批打折促发 @mo
       $pre_type1 = app::get('b2c')->_('FirstDiscount');
       $pre_type2 = app::get('b2c')->_('Fullofgifts');

        if(isset($aCondition['type2']) &&  $aCondition['type2'] ==$pre_type1)
        {
              
        //uset会释放元数组元素@mo
           //根据促销条件获取相应促销条件开始的时间
            $pre_rule = app::get('b2c')->model('sales_rule_order');
            $is_statue = "true";
            $filter_c = array('status|nequal'=>$is_statue,'rule_id'=>$rule['rule_id']);
            $all_promotion_rules = $pre_rule->getList('rule_id,name,conditions,from_time,to_time,action_conditions', $filter_c, 0, -1, 'rule_id ASC');
          // var_dump($all_promotion_rules);
  
    
           $member_id = kernel::single('b2c_user_object')->get_member_id();

            $db_order = app::get('b2c')->model('orders');
          if($all_promotion_rules)
          {
             $fromtime = $all_promotion_rules[0]['from_time'];
             $totime = $all_promotion_rules[0]['to_time'];
               
             $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime,'status|noequal'=>'dead');//modify by hzk 05-26 排除废单 status = dead

          }
          else
          {
             $filter = array('member_id'=>$member_id);//time: ,'createtime|bthan'=>$this_time
          }
       
           //根据当前的促销条件到订单中心去获取当前这个人已经购买的数量
            $this_member_all_orders = $db_order->getList('order_id,member_id', $filter, 0, -1, 'order_id ASC');

  
            $db_order_goods = app::get('b2c')->model('order_items');
            $gift_type = app::get('b2c')->_('product');

            $order_goods_nums = 0;//当前用户之前购买的数量
            foreach ($this_member_all_orders as $one_order) {
                $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$aCondition['conditions']['0']['value']);
                $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                if(!empty($temp_goods))
                {
                    $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                    
                }

                //能否促发首批打折的条件就是，当前用户以前购买该商品的数量是否小于限制
               //$order_goods_nums  与$aCondition['firstvalue']大小比较
            }
           
            $aOperator = $this->getOperator($aCondition['operator']);
         
         $less_than_all_nummber = kernel::single($aOperator['object'])->validate($aCondition['operator'], $aCondition['firstvalue'], $order_goods_nums);
        
        //判断当前货物是否属于促销条件的货物
         foreach ($cart_objects['object']['goods'] as $key => $value) {

             $in_action_condition_good_id = false;//标志当前货物是否是属于action_conditions中的货物
             $pre_good_id = explode('_',$value['obj_ident']);
			 // var_dump($pre_good_id[1]);
			 // var_dump($all_promotion_rules[0]['conditions']['conditions'][0]['conditions'][0]['value']);//['conditions'][0]['value']
			 // var_dump($all_promotion_rules[0]['action_conditions']['conditions'][0]['value']);//['conditions'][0]['value']
			 // var_dump($all_promotion_rules);//['conditions'][0]['value']
			 $promotion_goods_id =  array('0'=>$all_promotion_rules[0]['conditions']['conditions'][0]['conditions'][0]['value']);
			 // var_dump($promotion_goods_id);
			 // echo'cc';
			 // var_dump(in_array($pre_good_id[1],$promotion_goods_id));
			 
			 
             if(in_array($pre_good_id[1],$promotion_goods_id) )
             // if(in_array($pre_good_id[1],$all_promotion_rules[0]['conditions']['conditions'][0]['conditions'][0]['value']) )
             {
				 // echo 'xxxxxxxxssssss';
                $in_action_condition_good_id = true;
                break;
             }

         }
		 // var_dump($less_than_all_nummber);
		 // var_dump($in_action_condition_good_id);
         if($less_than_all_nummber && $in_action_condition_good_id)//同时符合购买数量小于首批限制的，同时货物在条件中的
                return true;

          // echo 'xxx002';
        }
         else if (isset($aCondition['type2']) &&  $aCondition['type2'] ==$pre_type2) {
           //这里是满赠促销限制购买数量
           //根据促销条件获取相应促销条件开始的时间
           $pre_rule = app::get('b2c')->model('sales_rule_order');
            $is_statue = "true";
            $filter_c = array('status|nequal'=>$is_statue,'rule_id'=>$rule['rule_id']);
            $all_promotion_rules = $pre_rule->getList('rule_id,name,conditions,from_time,to_time,action_conditions', $filter_c, 0, -1, 'rule_id ASC');
         
             $member_id = kernel::single('b2c_user_object')->get_member_id();

            $db_order = app::get('b2c')->model('orders');
          if($all_promotion_rules)
          {
             $fromtime = $all_promotion_rules[0]['from_time'];
             $totime = $all_promotion_rules[0]['to_time'];
               
             $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime,'status|noequal'=>'dead');//modify by hzk 05-26 排除废单 status = dead

          }
          else
          {
             $filter = array('member_id'=>$member_id);//time: ,'createtime|bthan'=>$this_time
          }
       
           //根据当前的促销条件到订单中心去获取当前这个人已经购买的数量
            $this_member_all_orders = $db_order->getList('order_id,member_id', $filter, 0, -1, 'order_id ASC');

  
            $db_order_goods = app::get('b2c')->model('order_items');
            $gift_type = app::get('b2c')->_('product');

            foreach ($this_member_all_orders as $one_order) {
                $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$aCondition['conditions']['0']['value'],'nums|bthan'=>$aCondition['value']);
                $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                if(!empty($temp_goods))
                {
                    $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                    
                }

            }
            $less_than_max_number = false;

            //判断当前最大的购买数量
             if($order_goods_nums < $aCondition['maxquantity'])
             {
                $lessvalue = $aCondition['maxquantity'] - $order_goods_nums;
                //20个买17个时 ，满5个才促发，剩余3个，代表永远促发不了
                if($lessvalue > $aCondition['value'] )
                    $less_than_max_number = true;
             }
			//modify by hzk 05-26
			//当有效数量小于触发数量则不再触发赠品 
             if($order_goods_nums > ($aCondition['maxquantity'] - $aCondition['value']))
             {
                    $less_than_max_number = false;
             }
             //modify end
             
            //当前购物车的数量是否大于促发条件商品数量

            
            //判断当前货物是否属于促销条件的货物
         foreach ($cart_objects['object']['goods'] as $key => $value) {

             $in_action_condition_good_id = false;//标志当前货物是否是属于action_conditions中的货物
             $pre_good_id = explode('_',$value['obj_ident']);
             if(in_array($pre_good_id[1],$all_promotion_rules[0]['action_conditions']['conditions'][0]['value']) )
             {
                $in_action_condition_good_id = true;
                break;
             }

         }
          
            if($in_action_condition_good_id && $less_than_max_number)
            {
                return true;
            }

        }
         else
        {
            //oCond:b2c_sales_order_aggregator_combine
            foreach ($cart_objects['object']['goods'] as $object) {
                if ($oCond->validate($object, $aCondition)) { 
                //判断当前条件的商品是否符合该促销条件
                    $total += (float) $this->getData($object, $aAttr['path']);

                }   
            }
        $aOperator = $this->getOperator($aCondition['operator']);
         return kernel::single($aOperator['object'])->validate($aCondition['operator'], $aCondition['value'], $total);
        }
        return false;
      
           
       
      
    }
}
?>
